<template>
    <!-- 有告警数据时显示时间线 -->
    <div v-if="paginatedAlarms.length > 0">
        <el-timeline>
            <el-timeline-item v-for="alarm in paginatedAlarms" :key="alarm.id"
                :type="getTimelineItemType(alarm.severityText)" :size="'large'">
                <div class="timeline-alarm-item">
                    <div class="timeline-header">
                        <span class="time">{{ alarm.update_time }}</span>
                        <el-tag :type="getTimelineItemType(alarm.severityText)" size="small">
                            {{ alarm.severityText }}
                        </el-tag>
                    </div>
                    <div class="timeline-content">
                        <div>
                            <h4>{{ alarm.title }}</h4>
                            <p>{{ alarm.location }} | {{ alarm.type }}</p>
                        </div>
                        <div class="timeline-actions">
                            <el-button v-permission="['handle_exceptions']" type="primary" size="small"
                                @click="openProcessDialog(alarm)">
                                处理
                            </el-button>
                            <el-dropdown v-permission="['handle_exceptions']" trigger="click"
                                @command="handleCommand($event, alarm)">
                                <el-button size="small">
                                    <i class="fa fa-ellipsis-v"></i>
                                </el-button>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item command="ignore">忽略告警</el-dropdown-item>
                                        <el-dropdown-item command="detail">查看详情</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                        </div>
                    </div>
                </div>
            </el-timeline-item>
        </el-timeline>

        <!-- 分页组件 -->
        <div class="pagination-container" v-if="totalAlarms > 0">
            <el-pagination v-model:current-page="currentPage" :hide-on-single-page="true" v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 50]" layout="total, sizes, prev, pager, next, jumper" :total="totalAlarms"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>

    <!-- 无告警数据时显示空状态 -->
    <div v-else class="empty-state">
        <el-empty description="暂无告警"></el-empty>
    </div>

    <!-- 处理告警对话框 -->
    <el-dialog v-model="processDialogVisible" title="处理告警" width="600px" @closed="handleProcessDialogClosed">
        <el-form :model="processForm" label-width="80px" ref="formRef">
            <el-form-item label="告警信息">
                <div class="alarm-detail">
                    <div class="detail-item">
                        <span class="label">告警名称：</span>
                        <span>{{ currentAlarm?.title }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">告警位置：</span>
                        <span>{{ currentAlarm?.location }}</span>
                    </div>
                    <div class="detail-item">
                        <span class="label">告警类型：</span>
                        <span>{{ currentAlarm?.type }}</span>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="处理说明" prop="description" :rules="[
                { required: true, message: '请输入处理说明', trigger: 'blur' }
            ]">
                <el-input v-model="processForm.description" type="textarea" rows="4" placeholder="请输入处理说明" />
            </el-form-item>

            <el-form-item label="处理图片">
                <el-upload class="upload-demo" action="#" :auto-upload="false" :on-change="handleFileChange"
                    :on-remove="handleFileRemove" :limit="5" multiple accept="image/*"
                    :file-list="processForm.fileList">
                    <template #trigger>
                        <el-button type="primary">选择图片</el-button>
                    </template>
                    <template #tip>
                        <div class="el-upload__tip">
                            支持jpg/png文件，最多可上传5张图片
                        </div>
                    </template>
                </el-upload>
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeProcessDialog">取消</el-button>
                <el-button type="primary" @click="submitProcess">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 告警详情对话框 -->
    <AlarmDetail v-model:visible="detailDialogVisible" :current-alarm="currentAlarm" @close="handleDetailClose" />
</template>

<script setup>
import dayjs from 'dayjs'
import { ref, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
// 导入API和组件
import { updateEventApi } from '@/api/event'
import { ElMessage } from 'element-plus'
import AlarmDetail from './components/AlarmDetail.vue'
const props = defineProps({
    alarms: {
        type: Array,
        default: () => []
    },
})

const emit = defineEmits(['refreshData'])

// 工具函数
const getTimelineItemType = (severity) => {
    const types = {
        '严重': 'danger',
        '警告': 'warning',
        '提示': 'primary'
    }
    return types[severity] || 'info'
}

// 告警数据，按时间排序（时间早的在前面）
const activeAlarms = computed(() => {
    return [...props.alarms].sort((a, b) => {
        const dateA = dayjs(a.time);
        const dateB = dayjs(b.time);
        return dateB.valueOf() - dateA.valueOf()
    });
})

// 总告警数量
const totalAlarms = computed(() => {
    return activeAlarms.value.length
})

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)

// 根据分页设置显示的告警
const paginatedAlarms = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    return activeAlarms.value.slice(startIndex, endIndex)
})

// 分页大小变化
const handleSizeChange = (size) => {
    pageSize.value = size
}

// 当前页变化
const handleCurrentChange = (page) => {
    currentPage.value = page
}

// 处理对话框相关
const processDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentAlarm = ref(null)
const formRef = ref(null)

// 处理表单数据
const processForm = reactive({
    description: '',
    fileList: []
})

// 打开处理对话框
const openProcessDialog = (alarm) => {
    currentAlarm.value = alarm
    processDialogVisible.value = true
}

// 打开详情对话框
const openDetailDialog = (alarm) => {
    currentAlarm.value = alarm
    detailDialogVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
    detailDialogVisible.value = false
    // 不要马上清除currentAlarm，等过渡动画结束后再清除
    setTimeout(() => {
        if (!processDialogVisible.value) {
            currentAlarm.value = null
        }
    }, 300)
}

// 文件上传相关方法
const handleFileChange = (file) => {
    if (!file.raw.type.startsWith('image/')) {
        ElMessage.error('只能上传图片文件！')
        return false
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

const handleFileRemove = (file) => {
    const index = processForm.fileList.indexOf(file)
    if (index !== -1) {
        processForm.fileList.splice(index, 1)
    }
}

// 处理对话框关闭
const handleProcessDialogClosed = () => {
    resetForm()
}

// 重置表单
const resetForm = () => {
    processForm.description = ''
    processForm.fileList = []
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

// 关闭处理对话框
const closeProcessDialog = () => {
    processDialogVisible.value = false
    // 如果详情对话框也未打开，则清除当前告警
    setTimeout(() => {
        if (!detailDialogVisible.value) {
            currentAlarm.value = null
        }
    }, 300)
}

// 提交处理
const submitProcess = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (valid && currentAlarm.value) {
            try {
                // 调用API更新事件状态为"已处理"(2)，并添加处理说明
                await updateEventApi({
                    id: currentAlarm.value.id,
                    status: 2,
                    info: processForm.description // 添加处理说明
                })

                // 通知父组件刷新数据
                emit('refreshData')

                ElMessage({
                    type: 'success',
                    message: '告警处理成功'
                })

                // 关闭对话框
                processDialogVisible.value = false
            } catch (error) {
                console.error('处理告警失败:', error)
                ElMessage.error('处理告警失败，请重试')
            }
        }
    })
}

// 处理下拉菜单命令
const handleCommand = async (command, alarm) => {
    if (command === 'ignore') {
        try {
            // 调用API更新事件状态为"已忽略"(3)，并添加忽略原因
            await updateEventApi({
                id: alarm.id,
                status: 3,
                info: '用户手动忽略' // 添加忽略原因
            })

            // 通知父组件刷新数据
            emit('refreshData')

            ElMessage({
                type: 'success',
                message: '已忽略该告警'
            })
        } catch (error) {
            console.error('忽略告警失败:', error)
            ElMessage.error('忽略告警失败，请重试')
        }
    } else if (command === 'detail') {
        // 打开详情对话框
        openDetailDialog(alarm)
    }
}
</script>

<style scoped>
.timeline-alarm-item {
    padding: 12px;
    background-color: var(--el-bg-color-page);
    border-radius: 4px;
}

.timeline-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
}

.timeline-content {
    margin-top: var(--gap-normal);
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.timeline-content h4 {
    margin: 0 0 4px 0;
}

.timeline-content p {
    margin: 0;
    color: var(--el-text-color-secondary);
    font-size: 13px;
}

.timeline-actions {
    display: flex;
    gap: 8px;
}

/* 空状态样式 */
.empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 500px;
    border-radius: 4px;
    padding: 20px;
}

.empty-icon {
    font-size: 60px;
    color: var(--el-color-success);
}

/* 处理对话框样式 */
.alarm-detail {
    width: 100%;
    padding: 16px;
    background-color: var(--el-fill-color-lighter);
    border-radius: 4px;
}

.detail-item {
    margin-bottom: 8px;
    font-size: 14px;
}

.detail-item .label {
    color: var(--el-text-color-secondary);
    margin-right: 8px;
}

/* 分页样式 */
.pagination-container {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
    padding: 10px 0;
}

:deep(.el-upload-list) {
    margin-top: 8px;
}

:deep(.el-upload__tip) {
    margin-top: 8px;
    color: var(--el-text-color-secondary);
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>